package com.helper.network

import com.App
import com.helper.utils.Md5Util
import com.sh.doctors.cloud.R
import com.sh.doctors.cloud.netconfig.DoctorsUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.*


/**
 * 页面描述：SasHeaderHandler
 *
 * Created by ditclear on 2017/12/18.
 */
open class DoctorsHeaderHandler : RequestHandler {
    override fun onBeforeRequest(request: Request, chain: Interceptor.Chain): Request {
        val map = getAuth(request.url().toString().replace(DoctorsUrl.BASE_URL, "/tod-web/"))
        val builer = chain.request().newBuilder()
            .addHeader("random", map.get("random").toString())
            .addHeader("timestamp", map.get("timestamp").toString())
            .addHeader("signature", map.get("signature").toString())
        return builer.build()
    }

    //获取秘钥
    fun getAuth(path: String): Map<String, String> {
        val random = Integer.toHexString(Random().nextInt(100000))
        val timestamp = Date().time.toString()
        val str = StringBuilder()
            .append(random) //随机数
            .append("_") //
            .append(path) //路径
            .append("+")//
            .append(timestamp)//时间戳
            .append("*")//
            .append(DoctorsUrl.secret)//秘钥
            .toString()
        val map = HashMap<String, String>()
        map.put("signature", Md5Util.md5(str))
        map.put("random", random)
        map.put("timestamp", timestamp)
        return map
    }

    @Throws(IOException::class)
    override fun onAfterRequest(response: Response, chain: Interceptor.Chain): Response {
        var e: ApiException? = null
        when {
            401 == response.code() -> {
                throw ApiException(401, App.instance.getString(R.string._401))
            }
            403 == response.code() -> e = ApiException(403, App.instance.getString(R.string._403))
            404 == response.code() -> e = ApiException(404, App.instance.getString(R.string._404))
            503 == response.code() -> e = ApiException(503, App.instance.getString(R.string._503))
            response.code() > 300 -> {
                val message = response.body()?.string()
                e = if (message?.isEmpty() != true) {
                    ApiException(
                        response.code(),
                        response.code().toString() + App.instance.getString(R.string.server_error)
                    )
                } else {
                    ApiException(response.code(), response.code().toString() + message)
                }
            }
        }
        e?.let {
            throw it
        }
        return response
    }
}